package com.aaa.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.entity.Log;
import com.aaa.service.LogService;
import com.aaa.util.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author ：admin
 * @date ：Created in 2022/7/5 18:37
 * @description：日志切面类
 * @modified By：
 */
@Component
@Aspect
@EnableAspectJAutoProxy
public class LogAspect {

    @Autowired
    private LogService logService;

    @Autowired
    HttpSession session;

    /**
     * 只写一次，多个方法调用
     */
    @Pointcut("execution(public * com.aaa.controller.*.*(..))")
    public void controller() {
    }

    @Around("controller()")
    public Object myEnhance(ProceedingJoinPoint joinPoint) {

        //获取方法的参数
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        Log log = new Log();

        //获取用户名
        if (ObjectUtil.isNotEmpty(session.getAttribute("user"))) {
            Map<String, Object> userMap = (Map<String, Object>) session.getAttribute("user");
            String username = (String) userMap.get("user_name");
            log.setUsername(username);
        }

        //获取请求的ip地址
        String ipAddress = IpUtil.getIpAddr();
        log.setIp(ipAddress);

        //获取类名
        String className = joinPoint.getTarget().getClass().getName();
        log.setClassName(className);

        //获取方法名
        String[] split = signature.toString().split("\\.");
        String methodName = split[split.length - 1];
        log.setMethodName(methodName);

        //获取参数
        String param = Arrays.toString(args);
        log.setParams(param);
        if (param.getBytes().length > 8889) {
            log.setParams("Too Long Params");
        }

        log.setCreateTime(new Date());

        logService.saveLog(log);

        try {
            Object proceed = joinPoint.proceed(args);
            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}
